package binary_tree


type MultiForkTreeNode struct {
	Value string
	Children []*MultiForkTreeNode
}

func NewMultiForkTreeNode(value string, children []*MultiForkTreeNode) *MultiForkTreeNode {
	return &MultiForkTreeNode{
		Value: value,
		Children: children,
	}
}

// MultiForkTreeEncode: 多叉树编码为二叉树  ------------------------------------
func MultiForkTreeEncode(mRoot *MultiForkTreeNode) *TreeNode {
	if mRoot == nil {
		return nil
	}
	binaryTreeRoot := NewTreeNode(mRoot.Value)
	binaryTreeRoot.Left = En2TreeNode(mRoot.Children)
	return binaryTreeRoot
}

func NewTreeNode(value string) *TreeNode {
	return &TreeNode{
		Value: value,
	}
}

func En2TreeNode(children []*MultiForkTreeNode) *TreeNode {
	var head, cur *TreeNode
	for _, c := range children {
		treeNode := NewTreeNode(c.Value)
		if head == nil {
			head = treeNode
		} else if cur != nil {
			cur.Right = treeNode
		}
		cur = treeNode
		cur.Left = En2TreeNode(c.Children)
	}
	return head
}

// BinaryTreeDecode2MultiForkTree: 二叉树解码为多叉树  ------------------------------------
func BinaryTreeDecode2MultiForkTree(root *TreeNode) *MultiForkTreeNode {
	return NewMultiForkTreeNode(root.Value, DeBinaryTree(root.Left))
}

func DeBinaryTree(treeNode *TreeNode) []*MultiForkTreeNode {
	ans := make([]*MultiForkTreeNode, 0)
	if treeNode == nil {
		return ans
	}
	cur := treeNode
	for cur != nil {
		mN := NewMultiForkTreeNode(cur.Value, DeBinaryTree(cur.Left))
		ans = append(ans, mN)
		cur = cur.Right
	}
	return ans
}